package com.jyy.prefabricated.service;

import com.alibaba.fastjson.JSONObject;
import com.jyy.prefabricated.dto.*;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.BaseStatusEnum;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.utils.XiaoeClient;
import com.jyy.prefabricated.vo.StudentsOfficialVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TrainingOrganizationMapper trainingOrganizationMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    /**
     * 新增用户
     *
     * @param dto
     * @return
     */
    public int createUser(SysUserDto dto) {
        //判断用户名是否重复
        SysUser checkUser = selectByUsernameOrIdCard(dto.getUsername());
        if (checkUser != null) {
            throw new CustomException("当前用户名或身份证号已存在！");
        }
        //加密密码
        String encodePwd = passwordEncoder.encode(dto.getPassword());
        SysUser user = new SysUser();
        BeanUtils.copyProperties(dto, user);
        user.setPassword(encodePwd);
        if(user.getInviter() != null && !"".equals(user.getInviter())){
            user.setBindingTime(new Date());
        }
        userMapper.insert(user);
        return user.getId();
    }
    /**
     * 新增用户(如果存在返回)
     *
     * @param dto
     * @return
     */
    public int createUserLogin(SysUserDto dto) {
        //判断用户名是否重复
        SysUser checkUser = selectByUsernameOrIdCard(dto.getUsername());
        if (checkUser != null) {
        return checkUser.getId();
        }
        //加密密码
        String encodePwd = passwordEncoder.encode(dto.getPassword());
        SysUser user = new SysUser();
        BeanUtils.copyProperties(dto, user);
        user.setPassword(encodePwd);
        if(user.getInviter() != null && !"".equals(user.getInviter())){
            user.setBindingTime(new Date());
        }
        userMapper.insert(user);
        return user.getId();
    }

    /**
     * 根据用户名或身份证号去匹配用户
     *
     * @param username
     * @return
     */
    public SysUser selectByUsernameOrIdCard(String username) {
        return userMapper.selectByUsernameOrIdCard(username);
    }

    /**
     * 根据openid去匹配用户
     *
     * @param openid
     * @return
     */
    public SysUser selectByOpenid(String openid) {
        return userMapper.selectByOpenid(openid);
    }


    /**
     * 通过用户名查询
     *
     * @param username
     * @return
     */
    public SysUser selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    /**
     * 更新用户
     *
     * @param dto
     * @return
     */
    public int update(SysUserDto dto) {
        if (dto.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        SysUser oldUser = userMapper.selectByPrimaryKey(dto.getId());
        if (oldUser != null && !oldUser.getId().equals(dto.getId())) {
            throw new CustomException("当前用户名或身份证号已存在！");
        }
        SysUser user = new SysUser();
        BeanUtils.copyProperties(dto, user);
        if(oldUser.getInviter()!=null && !"".equals(oldUser.getInviter())){
            user.setInviter(null);
        }
        if (dto.getPassword() !=null &&!dto.getPassword().equals(oldUser.getPassword())) {
            String encodePwd = passwordEncoder.encode(dto.getPassword());
            user.setPassword(encodePwd);
        }
        if(user.getInviter()!=null && !"".equals(user.getInviter())){
            user.setBindingTime(new Date());
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 更新用户
     *
     * @param sysUser
     * @return
     */
    public int update(SysUser sysUser) {
        if (sysUser.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        SysUser checkUser = selectByUsernameOrIdCard(sysUser.getUsername());

        if (checkUser != null && !checkUser.getId().equals(sysUser.getId())) {
            throw new CustomException("当前用户名或身份证号已存在！");
        }
        return userMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 修改用户状态
     *
     * @param id
     * @return
     */
    public int updateStatus(Integer id) {
        SysUser user = userMapper.selectByPrimaryKey(id);
        if (user.getStatus().equals(BaseStatusEnum.VALID.getValue())) {
            user.setStatus(BaseStatusEnum.INVALID.getValue());
        } else {
            user.setStatus(BaseStatusEnum.VALID.getValue());
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 重置密码
     *
     * @param id
     * @param newPwd 新密码
     * @return
     */
    public int resetPwdById(Integer id, String newPwd) {
        SysUser user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new CustomException("当前用户不存在！");
        }
        String md5pwd = passwordEncoder.encode(newPwd);
        user.setPassword(md5pwd);
        return userMapper.updateByPrimaryKey(user);
    }

    /**
     * 重置密码
     *
     * @param username 用户名
     * @param newPwd   新密码
     * @return
     */
    public int resetPwdByAccount(String username, String newPwd) {
        SysUser user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new CustomException("当前用户不存在！");
        }
        String md5pwd = passwordEncoder.encode(newPwd);
        user.setPassword(md5pwd);
        return userMapper.updateByPrimaryKey(user);
    }

    /**
     * 修改密码
     *
     * @param user
     * @param dto
     * @return
     */
    public int changePwd(SysUser user, ChangePwdDto dto) {
        if (!passwordEncoder.matches(dto.getOldPwd(), user.getPassword())) {
            throw new CustomException("旧密码不正确！");
        }
        String md5pwd = passwordEncoder.encode(dto.getNewPwd());
        user.setPassword(md5pwd);
        return userMapper.updateByPrimaryKey(user);
    }

    /**
     * 设置用户角色
     *
     * @param dto
     */
    public void putUserRoles(UserRoleDto dto) {
        //先清空用户当前的角色
        userRoleMapper.deleteByUserId(dto.getUserId());
        if (dto.getRoleIds().size() > 0) {
            List<UserRole> userRoles = new ArrayList<>();
            for (Integer roleId : dto.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(dto.getUserId());
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
            userRoleMapper.insert(userRoles);
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        SysUser sysUser = userMapper.selectByPrimaryKey(id);
        sysUser.setDeleted(true);
        return userMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public SysUser selectById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }




    /**
     * 查询
     *
     * @param keyword 关键字
     * @param status  状态
     * @return
     */
    public List<SysUser> selectByParams(String keyword, Integer status) {
        return userMapper.selectByParams(keyword, status, UserTypeEnum.ADMIN.getValue());
    }

    /**
     * 查询列表
     *
     * @return
     */
    public List<SysUser> selectByDto(StudentsOfficialDto dto) {

        return userMapper.selectByDto(dto);
    }
    public List<SysUser> allSelectSalesperson(SysUserDto dto) {
        dto.setUserType(UserTypeEnum.SALESPERSON.getValue());
        List<SysUser> sysUsers = userMapper.selectSalesperson(dto);
        return sysUsers;
    }
    /**
     * 查询列表
     *
     * @return
     */
    public List<SysUser> selectSalesperson(SysUserDto dto) {
        dto.setUserType(UserTypeEnum.SALESPERSON.getValue());
        List<SysUser> sysUsers = userMapper.selectSalesperson(dto);
        for (SysUser userItem:sysUsers) {
            Integer customerNum = userMapper.selectCustomerNum(userItem.getMobile());
            if(customerNum != null && customerNum != 0){
                userItem.setCustomerNum(customerNum);
                Integer courseOrder = userMapper.selectOrderNum(userItem.getMobile());
                if(courseOrder != null && courseOrder != 0){
                    userItem.setOrderNum(courseOrder);
                }else{
                    userItem.setOrderNum(0);
                }
            } else{
                userItem.setOrderNum(0);
                userItem.setCustomerNum(0);
            }

        }
        return sysUsers;
    }
    public SysUser selectSalesDetail(Integer id) {
        SysUser result = userMapper.selectByPrimaryKey(id);
        if(result != null){
            if(result.getMobile() != null && !"".equals(result.getMobile())){
                List<SysUser> sysUsers = userMapper.selectByInviter(result.getMobile());
                if(sysUsers != null){
                    result.setCustomerNum(sysUsers.size());
                    result.setCustomerList(sysUsers);
                    List<OrderInfo> orderInfos = orderInfoMapper.selectCusOrderList(result.getMobile());
                    if(orderInfos != null){
                        result.setOrderNum(orderInfos.size());
                        result.setOrderList(orderInfos);
                    }else{
                        result.setOrderNum(0);
                    }
                }else{
                    result.setCustomerNum(0);
                }

            }
        }
        return result;
    }
    public List<SysUser> selectByInviter(SysUserDto sysUserDto) {
        List<SysUser> sysUsers = userMapper.selectByInviter(sysUserDto.getMobile());
        return sysUsers;
    }

    public List<OrderInfo> selectOrderList(SysUserDto sysUserDto) {
        List<OrderInfo> orderInfos = orderInfoMapper.selectCusOrderList(sysUserDto.getMobile());
        return orderInfos;
    }
    /**
     * 查询详情
     *
     * @return
     */
    public StudentsOfficialVo selectByUserId(Integer id) {
        StudentsOfficialVo result = new StudentsOfficialVo();
        StudentsOfficialDto dto = new StudentsOfficialDto();
        dto.setId(id);
        List<SysUser> list = userMapper.selectByDto(dto);
        if (list != null && list.size() > 0) {
            if (list.get(0).getUserType().equals(UserTypeEnum.TRAININGORGANIZATION.getValue())) {
                TrainingOrganization trainingOrganization = trainingOrganizationMapper.selectByPrimaryKey(list.get(0).getTrainingOrganization().getId());
                BeanUtils.copyProperties(trainingOrganization, result);

                result.setUserType(UserTypeEnum.TRAININGORGANIZATION.getValue());

            } else if (list.get(0).getUserType().equals(UserTypeEnum.STUDENT.getValue())) {
                Student student = studentService.selectById(list.get(0).getStudent().getId());
                BeanUtils.copyProperties(student, result);

                result.setUserType(UserTypeEnum.STUDENT.getValue());
            }
        }
        result.setMobile(result.getTel());
        return result;
    }


    /**
     * 获取当前用户信息
     *
     * @return
     */
    public SysUser fetchUserInfo() {
        SysUser user = userUtils.getCurrentUser();

//        if (user.getUserId() == null || "".equals(user.getUserId())) {
//            //调用小鹅通注册新用户接口
//            String url = "https://api.xiaoe-tech.com/xe.user.register/1.0.0";
//            String data = "{" +
//                    " \"phone\":\"" +user.getUsername()  + "\"," +
//                    " \"wx_name\":\"" + user.getName() + "\"," +
//                    " \"gender\":" + user.getSex() +
//                    "}";
//            XiaoeClient client = new XiaoeClient();
//            Map result = client.request("post", url, data);
//            System.out.println(result);
//            JSONObject jsonObject = JSONObject.parseObject(result.toString());
//            // 获取到key为shoppingCartItemList的值
//            String resultData= jsonObject.getString("data");
//            JSONObject jsonObjectData = JSONObject.parseObject(resultData);
//            String userId= jsonObjectData.getString("user_id");
//            user.setUserId(userId);
//            userMapper.updateByPrimaryKeySelective(user);
//
//        }
        //获取当前用户状态启用的角色
        List<SysRole> roles = user.getRoles().stream().filter(e -> e.getStatus().equals(BaseStatusEnum.VALID.getValue())).collect(Collectors.toList());
        List<Integer> ids = roles.stream().map(e -> e.getId()).collect(Collectors.toList());
        if (ids.size() > 0) {
            List<SysPermission> permissions = permissionMapper.selectByRoleIds(ids);
            user.setPermissions(permissions.stream().filter(e -> e.getStatus().equals(BaseStatusEnum.VALID.getValue())).collect(Collectors.toList()));
        }
        return user;
    }
}
